import React, { createContext, useState, useMemo } from 'react';
import { translations } from '../localization/strings';
import type { TranslationSet } from '../types';

interface LocalizationContextType {
    language: string;
    setLanguage: (language: string) => void;
    t: (key: string, options?: { [key: string]: string | number }) => any;
    getLocalizedPath: (path: string) => string;
}

export const LocalizationContext = createContext<LocalizationContextType | undefined>(undefined);

export const LocalizationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [language, setLanguage] = useState('en');

    const t = useMemo(() => (key: string, options?: { [key: string]: string | number }) => {
        const langTranslations = translations[language] || translations['en'];
        let text = key.split('.').reduce((obj: any, i) => obj?.[i], langTranslations);

        if (typeof text === 'undefined') {
            console.warn(`Translation key "${key}" not found for language "${language}"`);
            // Fallback to English
            text = key.split('.').reduce((obj: any, i) => obj?.[i], translations['en']);
            if (typeof text === 'undefined') {
                return key;
            }
        }
        
        if (typeof text === 'string' && options) {
            Object.keys(options).forEach(optKey => {
                text = text.replace(new RegExp(`{${optKey}}`, 'g'), String(options[optKey]));
            });
        }

        return text;
    }, [language]);

    const getLocalizedPath = useMemo(() => (path: string) => {
        const isRoot = path === '/';
        // Get the base path, ensuring it starts with a slash if it's not the root path
        const basePath = isRoot ? '' : (path.startsWith('/') ? path : `/${path}`);
        
        if (language === 'en') {
            // For English, return the root path as is, or the base path for other pages
            return isRoot ? '/' : basePath;
        }
        
        // For other languages, prefix with the language code
        return `/${language}${basePath}`;
    }, [language]);


    const value = {
        language,
        setLanguage,
        t,
        getLocalizedPath,
    };

    return (
        <LocalizationContext.Provider value={value}>
            {children}
        </LocalizationContext.Provider>
    );
};